import { defineStore } from "pinia";
import { ref, computed } from "vue";
import {useRouter} from "vue-router";
import { useUserStore } from "@/stores/userStore";
import { delHistoryAPI, findHistoryByIdAPI, insertHistoryAPI } from "@/apis/history.js";

export const useHistoryStore = defineStore(
    'history',
    () => {
        const historyList = ref([]);
        const userStore = useUserStore();
        const router = useRouter();

        // 获取登录后最新收藏夹列表action
        const updateLoginHistoryList = async () => {
            const res = await findHistoryByIdAPI(userStore.userInfo.userId)
            let updatedHistoryList = Array.isArray(res.data) ? res.data : [];
            historyList.value = updatedHistoryList;
        }

        const addHistory = async (userId,productId) => {
            await insertHistoryAPI(userId,productId)
            await updateLoginHistoryList()
        }
        const delHistory = async (userId,productId) => {
            await delHistoryAPI(userId,productId)
            await updateLoginHistoryList()
        }
        
        return {
            historyList,
            addHistory,
            delHistory,
            updateLoginHistoryList,
        }
    },
    {
        persist: true
    }
)